<script>
import config from "../../config";
import { getJmxList, getRemoteMachines, executeRemoteMachine, uploadJmxFiles} from "../api/jmxApi";
import { getProductList, getProjectList } from "../api/harApi";
import { ElMessage } from "element-plus";

export default {
    name: "JmxPage",

    data() {
        return {
            products: [],
            projects: [],
            jmxs: [],
            machines: [],

            input: {
                uuid: this.$route.query.uuid || "",
            },

            select: {
                productId: null,
                projectId: null
            },

            dialog: {
                uploadJmxFiles: {
                    visible: false,
                    title: "上传JMX文件",
                    form: {
                        uuid: "",
                        procectName: "",
                        projectName: "",
                        jmxFiles: []
                    },
                },
                execution: {
                    visible: false,
                    title: "执行",
                    form: {
                        machineUuid: "",
                        jmxUuid: "",
                        testPlans: [],
                        duration: "",
                        maxRound: "",
                    }
                },
            }
        };
    },

    async mounted() {
        this.products = (await getProductList()).data;
        this.projects = (await getProjectList()).data;
        this.jmxs = (await getJmxList({
            uuid: this.input.uuid,
            productId: this.select.productId,
            projectId: this.select.projectId
        })).data;
    },

    methods: {
        async handleQueryJmxList() {
            this.jmxs = (await getJmxList({
                uuid: this.input.uuid,
                productId: this.select.productId,
                projectId: this.select.projectId
            })).data;
        },

        async handleClickExecuteButton(row) {
            this.machines = (await getRemoteMachines()).data.filter(machine => machine.machineStatus === "idle");
            this.dialog.execution.form.machineUuid = "";
            this.dialog.execution.form.jmxUuid = row.uuid;
            this.dialog.execution.form.testPlans = row.jmxList.map(jmx => {
                return {
                    testPlanName: jmx.testPlanName,
                    initialThreadNumber: null,
                    threadNumberIncrement: null,
                }
            });
            this.dialog.execution.form.duration = "";
            this.dialog.execution.form.maxRound = "";
            this.dialog.execution.visible = true;
        },

        async handleSubmitExecutionForm() {
            const executionUuid = (await executeRemoteMachine(this.dialog.execution.form)).data.executionUuid;
            ElMessage({
                message: "提交执行成功",
                type: "success"
            });
            this.dialog.execution.visible = false;
            this.$router.push({ path: "/execution", query: { executionUuid } });
        },

        handleDownloadJmxFiles(jmxFilePaths) {
            const baseUrl = config.service.baseURL;
            jmxFilePaths.forEach((jmxFilePath, index) => {
                setTimeout(() => {
                    const downloadUrl = `${baseUrl}/${jmxFilePath}`;
                    const link = document.createElement('a');
                    link.href = downloadUrl;
                    const fileName = jmxFilePath.split('/').pop();
                    link.setAttribute("download", fileName);
                    document.body.appendChild(link);
                    link.click();
                    setTimeout(() => {
                        document.body.removeChild(link);
                    }, 100);
                }, index * 200);
            });
        },

        handleClickUploadButton(row) {
            this.dialog.uploadJmxFiles.form.uuid = row.uuid;
            this.dialog.uploadJmxFiles.form.procectName = row.productName;
            this.dialog.uploadJmxFiles.form.projectName = row.projectName;
            this.dialog.uploadJmxFiles.form.jmxFiles = [];
            this.dialog.uploadJmxFiles.visible = true;
        },

        async handleSubmitUploadJmxFilesForm() {
            const formData = new FormData();
            formData.append("uuid", this.dialog.uploadJmxFiles.form.uuid);
            this.dialog.uploadJmxFiles.form.jmxFiles.forEach(jmxFile => {
                jmxFile = new File([jmxFile.raw], encodeURIComponent(jmxFile.name), { type: jmxFile.type });
                formData.append("jmxFiles", jmxFile);
            });
            const data = await uploadJmxFiles(formData);
            if (data) {
                ElMessage({
                    message: "上传成功",
                    type: "success"
                });
            }
            this.dialog.uploadJmxFiles.visible = false;
        },

        handleClearUploadJmxFilesForm() {
            this.dialog.uploadJmxFiles.form.uuid = "";
            this.dialog.uploadJmxFiles.form.jmxFiles = [];
            this.dialog.uploadJmxFiles.visible = false;
        }

    }
}
</script>

<template>
    <div class="jmx-page">
        <div class="toolbar">
            <el-input v-model="input.uuid" clearable placeholder="uuid" class="input-item"></el-input>
            <el-select v-model="select.productId" placeholder="请选择产品" class="select-item" clearable>
                <el-option v-for="product in products" :key="product.productId" :label="product.productName"
                    :value="product.productId"></el-option>
            </el-select>
            <el-select v-model="select.projectId" placeholder="请选择项目" class="select-item" clearable>
                <el-option v-for="project in projects" :key="project.projectId" :label="project.projectName"
                    :value="project.projectId"></el-option>
            </el-select>
            <el-button @click="handleQueryJmxList" class="toolbar-button">查询</el-button>
        </div>
        <div class="table-container">
            <el-table :data="jmxs" class="jmx-table" height="100%">
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="uuid" label="UUID" width="300"></el-table-column>
                <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
                <el-table-column prop="projectName" label="项目名称" width="150"></el-table-column>
                <el-table-column label="测试计划" width="150">
                    <template #default="{ row }">
                        <span v-for="(jmx, index) in row.jmxList" :key="index">
                            <el-link @click="handleDownloadJmxFiles(jmx.jmxFilePaths)" type="primary" class="download-link">
                                {{ jmx.testPlanName }}
                            </el-link>
                            <br v-if="index < row.jmxList.length - 1">
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" width="200"></el-table-column>
                <el-table-column prop="updatedAt" label="更新时间" width="200"></el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" @click="handleClickUploadButton(row)" class="action-button" size="small">上传</el-button>
                        <el-button type="primary" @click="handleClickExecuteButton(row)" disabled class="action-button" size="small">执行</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <el-dialog v-model="dialog.uploadJmxFiles.visible" :title="dialog.uploadJmxFiles.title"
                @close="handleClearUploadJmxFilesForm" class="custom-dialog">
                <el-form :model="dialog.uploadJmxFiles.form" label-width="100px">
                    <el-form-item label="产品名称">
                        <el-input v-model="dialog.uploadJmxFiles.form.procectName" disabled />
                    </el-form-item>
                    <el-form-item label="项目名称">
                        <el-input v-model="dialog.uploadJmxFiles.form.projectName" disabled />
                    </el-form-item>
                    <el-form-item label="UUID">
                        <el-input v-model="dialog.uploadJmxFiles.form.uuid" disabled />
                    </el-form-item>
                    <el-form-item label="JMX文件">
                        <el-upload v-model:file-list="dialog.uploadJmxFiles.form.jmxFiles" :multiple="true" accept=".jmx"
                            :auto-upload="false">
                            <el-button>点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                    <div class="dialog-footer">
                        <el-button @click="handleClearUploadJmxFilesForm">取消</el-button>
                        <el-button type="primary" @click="handleSubmitUploadJmxFilesForm">提交</el-button>
                    </div>
                </el-form>
            </el-dialog>
            <el-dialog v-model="dialog.execution.visible" :title="dialog.execution.title" class="custom-dialog">
                <el-form :model="dialog.execution.form" label-width="100px">
                    <el-form-item label="远程机">
                        <el-select v-model="dialog.execution.form.machineUuid" placeholder="请选择远程机">
                            <el-option v-for="machine in machines" :key="machine.machineUuid" :label="machine.machineName"
                                :value="machine.machineUuid">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="JMX">
                        <el-input v-model="dialog.execution.form.jmxUuid" placeholder="请输入jmx uuid" disabled />
                    </el-form-item>
                    <el-form-item v-for="testPlan in dialog.execution.form.testPlans" :label="testPlan.testPlanName"
                        :key="testPlan.testPlanName">
                        <el-input v-model.number="testPlan.initialThreadNumber" placeholder="请输入初始线程数" type="number" />
                        <el-input v-model.number="testPlan.threadNumberIncrement" placeholder="请输入新增线程数" type="number" />
                    </el-form-item>
                    <el-form-item label="持续时间">
                        <el-input v-model.number="dialog.execution.form.duration" placeholder="请输入持续时间" type="number" />
                    </el-form-item>
                    <el-form-item label="最大轮次">
                        <el-input v-model.number="dialog.execution.form.maxRound" placeholder="请输入最大轮次" type="number" />
                    </el-form-item>
                    <div class="dialog-footer">
                        <el-button @click="dialog.execution.visible = false">取消</el-button>
                        <el-button type="primary" @click="handleSubmitExecutionForm">提交</el-button>
                    </div>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<style scoped>
.jmx-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.input-item {
  width: 300px;
}

.select-item {
  width: 180px;
}

.toolbar-button {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}

.toolbar-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: white;
}

.table-container {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.jmx-table {
  border: none;
  flex: 1;
}

.jmx-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.download-link {
  font-size: 14px;
}

.action-button {
  padding: 6px 12px;
  margin-right: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.custom-dialog :deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.custom-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px;
}
</style>